package com.hry.sunflower.images.service.impl;

import com.hry.sunflower.images.config.ImageProperties;
import com.hry.sunflower.images.exception.BusinessException;
import com.hry.sunflower.images.service.ImageService;
import com.hry.sunflower.images.utils.ImageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * @Desc
 * @Author houry
 * @Date 2021/1/25 9:23
 **/
@Service
@Slf4j
public class ImagesServiceImpl implements ImageService {

    @Resource
    private ImageProperties imageProperties;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 上传结果
     */
    @Override
    public String dealImage(MultipartFile file, double size) {
        try {
            if (ImageUtils.isImage(file.getInputStream())) throw new BusinessException("非图片信息");
            File originFile = new File(imageProperties.getOriginPath() + file.getOriginalFilename());
            file.transferTo(originFile);
            // 计算压缩比例
            double a = size * 1_024 / file.getSize() >= 1 ? 1 : size * 1_024 / file.getSize();
            File compression = ImageUtils.compression(imageProperties.getStorePath(), originFile, a);
            return compression.getPath();
        } catch (IOException e) {
            log.error("[ImagesServiceImpl]-[uploadImage]-[file = {}]-[IOException]", file.getOriginalFilename(), e);
        }
        return "";
    }
}
